package dao.impl;

import dao.UserDao;
import pojo.User;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class UserDaoImpl implements UserDao {
    @Override
    public List<User> findAll() {
        //jdbc查询数据库操作
        List<User> users=new ArrayList<>();

        String URL = "jdbc:mysql://127.0.0.1:3306/jdbc?characterEncoding=utf-8";
        String USER = "root";
        String PASSWORD = "Xlz922?*";

        // 1.加载驱动程序
        try {
            Class.forName("com.mysql.jdbc.Driver");
            // 2.获得数据库链接
            Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
            if (conn!=null){
                System.out.println("连接成功");
            }
            // 3.通过数据库的连接操作数据库，实现增删改查（使用Statement类）
            //预编译
            String sql = "select * from user";
            PreparedStatement preparedStatement = conn.prepareStatement(sql);
            //statement.setString(1, name);
            ResultSet rs = preparedStatement.executeQuery();

            // 4.处理数据库的返回结果(使用ResultSet类)
            while (rs.next()) {
                User user=new User();
                user.setId(rs.getInt(1));
                user.setName(rs.getString(2));
                user.setPass(rs.getString(3));
                users.add(user);
            }
            rs.close();
            preparedStatement.close();
            conn.close();
            // 关闭资源
            return users;
        } catch (ClassNotFoundException e){
            throw new RuntimeException(e);
        }catch (SQLException e){
            throw new RuntimeException(e);
        }

    }
}
